﻿using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.UI;

public static partial class Tools
{
    #region 检查资源是否存在

    private static Dictionary<string, bool> s_ResourcesExistDict = new Dictionary<string, bool>();

    /// <summary>
    /// 检查资源是否存在
    /// </summary>
    public static async UniTask<bool> CheckResourceExistAsync(string resourcePath)
    {
        if (!s_ResourcesExistDict.TryGetValue(resourcePath, out var exist))
        {
            var locations = await Addressables.LoadResourceLocationsAsync(resourcePath).Task;
            exist = locations.Count > 0;
            s_ResourcesExistDict[resourcePath] = exist;
        }
        return exist;
    }

    #endregion

    #region 加载Sprite资源

    private const string PREFAB_ROOT_PATH = "Sprites/{0}.png";
    private static AssetCache<string, Sprite> s_SpriteAssetCaches = new AssetCache<string, Sprite>(PREFAB_ROOT_PATH);

    /// <summary>
    /// 加载 sprite 资源。
    /// 需要资源存在于 Addressable/Sprites/ 路径下
    /// </summary>
    public static async UniTask LoadSpriteAsync(Image image, string spriteName, string fallback = null, bool setNativeSize = false, CancellationToken cancellationToken = default)
    {
        image.enabled = false;
        image.sprite = null;
        if (string.IsNullOrEmpty(spriteName)) return;
        if (cancellationToken.IsCancellationRequested) return;
        var sprite = await s_SpriteAssetCaches.LoadAsync(spriteName);
        if (sprite == null && !string.IsNullOrEmpty(fallback))
        {
            if (cancellationToken.IsCancellationRequested) return;
            sprite = await s_SpriteAssetCaches.LoadAsync(fallback);
        }
        if (image == null) return;
        if (cancellationToken.IsCancellationRequested) return;
        image.sprite = sprite;
        image.enabled = image.sprite != null;
        if (image.sprite == null) return;
        if (setNativeSize)
            image.SetNativeSize();
    }

    /// <summary>
    /// 加载 sprite 资源。
    /// 需要资源存在于 Addressable/Sprites/ 路径下
    /// </summary>
    public static async UniTask LoadSpriteAsync(SpriteRenderer spriteRenderer, string spriteName, string fallback = null, CancellationToken cancellationToken = default)
    {
        if (cancellationToken.IsCancellationRequested) return;
        var sprite = await s_SpriteAssetCaches.LoadAsync(spriteName);
        if (cancellationToken.IsCancellationRequested) return;
        spriteRenderer.sprite = sprite;
        if (sprite == null && !string.IsNullOrEmpty(fallback))
        {
            if (cancellationToken.IsCancellationRequested) return;
            var fallbackSprite = await s_SpriteAssetCaches.LoadAsync(fallback);
            if (cancellationToken.IsCancellationRequested) return;
            spriteRenderer.sprite = fallbackSprite;
        }
    }

    #endregion
}